/**
 * Created by leiweibo on 7/25/15.
 */

'use strict'

var app = angular.module('labfeecontroller', []);


app.controller('LabFeeCtrl',
  function( $scope, $window, $filter, PatientService, ProvinceService, HospitalService, LabFeeService) {

    var options = {
      'expiration': Math.floor(new Date().getTime() / 1000) + 86400,
      bucket: 'vistrack-attach-prd',
      'save-key': '/{filemd5}{.suffix}'
    };
    // 查看更多参数：http://docs.upyun.com/api/form_api/#表单API接口简介
    var policy = window.btoa(JSON.stringify(options));
    // 从 UPYUN 用户管理后台获取表单 API
    var form_api_secret = '5ri+TpAfi0lw+O9eaH9PBMYoSHI=';
    // 计算签名
    var signature = md5(policy + '&' + form_api_secret);
    var url_prefix = "http://" + options.bucket + ".b0.upaiyun.com";
    var pageState;
    var uploader = new plupload.Uploader({
      runtimes: 'html5,flash,silverlight,html4',
      browse_button: 'browser_detail', // you can pass in id...
      container: document.getElementById('container_detail'),
      flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
      silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',
      multi_selection:false,
      url: 'http://v0.api.upyun.com/' + options.bucket,

      multipart_params: {
        'Filename': '${filename}', // adding this to keep consistency across the runtimes
        'Content-Type': '',
        'policy': policy,
        'signature': signature
      },

      init: {
        PostInit: function () {
          //do nothing here.
        },

        FilesAdded: function (up, files) {
          plupload.each(files, function (file) {
            uploader.start();
          });
        },

        UploadProgress: function (up, file) {
          $('#percentage').text(file.percent + "%");
        },

        FileUploaded: function (up, file, info) {
          var response = JSON.parse(info.response);
          $scope.url = url_prefix + response.url;
        },

        Error: function (up, err) {
          $("#percentage").text("上传失败");
        }
      }
    });
    uploader.init();

    $scope.$watch('time', function (newValue) {
      $scope.time = $filter('date')(newValue, 'yyyy/MM/dd');
    });

    $scope.provinces = ProvinceService.list(function(data) {
      $scope.provinces = data.provinces
    });

    $scope.provinceChanged = function(provinceId) {
      $scope.hospitals = HospitalService.list_by_province(provinceId, function(res) {
        if (res.result == false) {
          $scope.error_msg = res.message;
        }
        $scope.hospitals = res.hospitals;
      });
    }


    $scope.createOrUpdate = function() {
      var formData = {
        province: $scope.province,
        hospital: $scope.hospital,
        detail: $scope.detail,
        url: $scope.url,
        time: $scope.time,
        fee: $scope.fee,
        hospital_contact: $scope.hospital_contact
      };

      console.log(formData);

      LabFeeService.create(formData, function (res) {
        if (res.result == true) {

          delete $scope.province
          delete $scope.hospital
          delete $scope.detail
          delete $scope.url
          delete $scope.time
          delete $scope.fee
          delete $scope.hospital_contact

          alert('添加实验室费用信息成功');
        } else {
          $scope.error_msg = res.message;
        }
      }, function (data, status) {
        $scope.error_msg = '无权限进行此操作';
      });
    }

    var province;
    var hospital;

    $scope.search = function() {
      province = $scope.province;
      hospital = $scope.hospital;

      $scope.callServer();
    }

    $scope.callServer = function (tableState) {
      if (!tableState) {
        tableState = pageState
        tableState.pagination.start = 0;
      } else {
        pageState = tableState;
      }

      $scope.isLoading = true;

      var pagination = tableState.pagination;
      var pageSize = pagination.number || 20;
      var pageNo = Math.ceil((pagination.start + 1) / pageSize) || 1;
      LabFeeService.list(province, hospital, pageNo, pageSize, tableState, function (res) {
        $scope.displayed = res.lab_fees;
        tableState.pagination.numberOfPages = res.pageCount;
        $scope.isLoading = false;
      });
    };

    $scope.role = $window.sessionStorage.role;
    $scope.hospital = $window.sessionStorage.hospital;
  });
